let selectedText = "";
let lastAnswer = "";
let conversationHistory = [];

// 初始化函数
function init() {
    console.log("Background script initialized");
}

// 处理与API的交互
function interactWithAPI(text, openNewPopup, sendResponse) {
    conversationHistory.push({ role: "user", content: text });

    const requestBody = {
        model: 'gpt-3.5-turbo',
        messages: conversationHistory
    };

    fetch('http://localhost:8083/api/chat/ask', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
    })
        .then(response => response.json())
        .then(data => {
            const answer = data.choices && data.choices.length > 0 ? data.choices[0].message.content : "No answer received.";
            conversationHistory.push({ role: "assistant", content: answer });
            lastAnswer = answer;

            if (openNewPopup) {
                openPopupWindow();
            }

            sendResponse({answer: answer});
        })
        .catch(error => {
            console.error('API Error:', error);
            lastAnswer = `An error occurred: ${error.message}`;
            sendResponse({answer: lastAnswer});
        });
}

// 创建一个新的popup窗口
function openPopupWindow() {
    chrome.windows.getCurrent(function(currentWindow) {
        const width = 500;
        const height = 410;
        const top = Math.round((currentWindow.height - height) / 2);
        const left = Math.round((currentWindow.width - width) / 2);

        chrome.windows.create({
            url: chrome.runtime.getURL("html/popup.html"),
            type: "popup",
            width: width,
            height: height,
            top: top,
            left: left
        });
    });
}

// 监听来自content scripts、popup等的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    switch (request.message) {
        case "text_selected":
            selectedText = request.data;
            interactWithAPI(selectedText, true, sendResponse);
            return true;  // 表示异步响应

        case "popup_chat":
            interactWithAPI(request.data, false, sendResponse);  // 不打开新窗口
            return true;  // 表示异步响应

        case "get_selected_text":
            sendResponse({ selectedText: selectedText, answer: lastAnswer });
            break;

        default:
            break;
    }
});

// 修改响应头以适应内容安全策略
chrome.webRequest.onHeadersReceived.addListener(
    function(details) {
        for (let i = 0; i < details.responseHeaders.length; i++) {
            if (details.responseHeaders[i].name.toLowerCase() === "content-security-policy") {
                details.responseHeaders[i].value = "default-src 'self' 'unsafe-inline' 'unsafe-eval' *; object-src 'self';";
            }
        }
        return { responseHeaders: details.responseHeaders };
    },
    { urls: ["http://*/*", "https://*/*"] },
    ["responseHeaders"]
);

// 初始化函数调用
init();
